<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2019/2/13
 * Time: 15:30
 */

namespace App\HttpController\Admin;

use App\Model\AdminsOpenidModel;
use App\Model\CategorysModel;
use App\Model\TmplmsgsModel;
use App\Utility\Cache;
use App\Utility\MiniProgram;
use App\Utility\Music;
use Carbon\Carbon;

class ArticleController extends AuthController
{
    public function index(){
        $request = $this->request();
        $params = $request->getRequestParam();
        if(!isset($params['applet'])){
            return $this->writeJson(1,null,'参数不正确！');
        }
        $appletModel = $this->appletArticleModel($params['applet']);
        $model = new $appletModel;
        //获取用户可推送模板id数量
        switch ($params['sort']) {
            case 1:
                $sort = 'view';
                break;
            case 2:
                $sort = 'share';
                break;
            default:
                $sort = 'id';
                break;
        }
        $params['page'] = $params['page'] ?: 1;
        $params['title'] = trim($params['title']) ?: '';
        $params['userid'] = $params['userid'] ?: 0;
        $params['is_link'] = $params['is_link'] ?? 0;
        $params['hot'] = $params['hot'] ?? 0;
        $params['lock'] = $params['lock'] ?? 0;
        $params['start'] = $params['start'] ?: '';
        $params['end'] = $params['end'] ?: '';
        $columns = 'articles_'.$params['applet'].'.id,cateid,title,articles_'.$params['applet'].'.thumb,articles_'.$params['applet'].'.created_at,articles_'.$params['applet'].'.status,
        userid,articles_'.$params['applet'].'.share,articles_'.$params['applet'].'.view,articles_'.$params['applet'].'.hot,articles_'.$params['applet'].'.lock,articles_'.$params['applet'].'.is_link,articles_'.$params['applet'].'.link_url,c.name,a.nickname';
        $userId = $this->userid;
        $lists = $model->select($columns)->where(function ($query) use($params,$userId){
            if($params['title']) $query->whereLike('title',$params['title']);
            if($params['userid']) $query->where('userid',$params['userid']);
            if($params['is_link']) $query->where('is_link',$params['is_link']);
            if($params['hot']) {
                $query->where('hot',$params['hot']);
            }
            if($params['lock']){
                $query->where('`lock`',$params['lock']);
            }
            if($params['start']) $query->whereDate('articles_'.$params['applet'].'.created_at',$params['start'],'>=');
            if($params['end']) $query->whereDate('articles_'.$params['applet'].'.created_at',$params['end'],'<=');
        })
            ->join('`categorys` as c', 'c.id = articles_'.$params['applet'].'.cateid','RIGHT')
            ->join('`admins` as a', 'a.id = articles_'.$params['applet'].'.userid','INNER')
            ->orderBy($sort)
            ->paginate($params['page'],8);
        foreach ($lists['data'] as $key => &$item){
            $item['pre'] = $item['share'] ? round((($item['share']/$item['view'])*10000)/100,2).'%' : '0%';
        }
        $this->stateToText($lists['data'],[
            'status' => $model::STATUS_TEXT,
        ]);
        //获取用户openID
        $adminOpenid = (new AdminsOpenidModel())->getAdminOpenid($params['applet'],$this->userid);
        //获取用户可推送模板id数量

        //判断是否有可以formId
        $cache =  new Cache();
        //根据openid取找到相应的openid的formid的集合，先删除该集合已过期的所有的formid,
        $cache->zRemRangeByScore($adminOpenid,0,time()+10);
        //然后取集合的成员数
        $lists['count_formid'] = $cache->zCard($adminOpenid);
        return $this->writeJson(0,$lists);
    }

    /**
     * 详情
     * @return bool
     * @throws \Throwable
     */
    public function info(){
        $request = $this->request();
        $id = $request->getRequestParam('id') ?? 0;
        $applet = $request->getRequestParam('applet') ?? '';
        if(empty($id) || !$applet){
            return $this->writeJson(1,null,'参数错误');
        }
        $appletModel = $this->appletArticleModel($applet);
        $model = new $appletModel;
        $info = $model->select('id,cateid,title,title_color,thumb,music_name,backimg,hot,`lock`,is_link,link_url,status,music,content')->find($id);
        return $this->writeJson(0,$info);
    }

    /**
     * 更新
     * @return bool
     * @throws \Throwable
     */
    public function update(){
        $request = $this->request();
        $data = $request->getRequestParam();
        //验证音乐编号的正确性
        $res = (new Music())->getMusic($data['music']);
        if($res === false){
            return $this->writeJson(1,null,'音乐编号不能解析，请重新填写');
        }
        if(!isset($data['applet'])){
            return $this->writeJson(1,null,'参数不正确！');
        }
        if(isset($data['content'])){
            $data['content'] = str_replace('tp=webp','tp=jpg',$data['content']);
            $data['content'] =  preg_replace('/<img.*?src="(.*?)".*?>/is','<img src="$1" style="max-width: 100%;"/>', $data['content']);
        }
        $appletModel = $this->appletArticleModel($data['applet']);
        $model = new $appletModel;
        $data['userid'] = $this->userid;
        if($data['id']){
            $infoID = $model->find($data['id']);
            if(!$infoID){
                return $this->writeJson(1,null,'数据不存在');
            }
            unset($data['userid']);
            //修改
            $model->update($data);
            return $this->writeJson(0,null,'编辑成功');
        }else{
            //新增
            $data['created_at'] = Carbon::now();
            $data['userid'] = $this->userid;
            $data['rand'] = rand(1,10);
            $cmodel = new CategorysModel();
            $cate = $cmodel->where('type',1)->inRandomOrder()->first();
            $data['cateid'] = $cate['id'];
            $model->create($data);
            return $this->writeJson(0,null,'新增成功');
        }
    }

    /**
     * 删除
     * @return bool
     * @throws \Throwable
     */
    public function destroy(){
        $request = $this->request();
        $id = $request->getRequestParam('id');
        $applet = $request->getRequestParam('applet') ?? '';
        if(!$applet){
            return $this->writeJson(1,null,'参数不正确！');
        }
        $appletModel = $this->appletArticleModel($applet);
        $model = new $appletModel;
        if(is_array($id)){
            $model->whereIn('id',$id)->delete();
        }else{
            $model->destroy($id);
        }
        return $this->writeJson(0);
    }

    /**
     * 模板推送，手机预览
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\OrderByFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function preview(){
        $request = $this->request();
        $id = $request->getRequestParam('id') ?: 0;
        $applet = $request->getRequestParam('applet') ?? '';

        if(empty($id) || !$applet){
            return $this->writeJson(1,null,'参数错误！');
        }
        $configAppletName = $this->appletConfigModel($applet);
        $configModel = new $configAppletName;
        $template_id = $configModel->where('name','template_id')->first();
        if(!$template_id){
            return $this->writeJson(1,null,'请【配置管理】添加template_id');
        }
        //获取用户openID
        $adminOpenid = (new AdminsOpenidModel())->getAdminOpenid($applet,$this->userid);
        if(!$adminOpenid){
            return $this->writeJson(1,null,'请联系技术人员添加openID！');
        }
        $appletAritcleName = $this->appletArticleModel($applet);
        $articleModel = new $appletAritcleName;
        $articlesInfo = $articleModel->find($id);

        if($articlesInfo['is_link'] == 2){
            $prama = 'url='.$articlesInfo['link_url'];
        }else{
            $prama = 'id='.$id;
        }
        $model = new TmplmsgsModel();
        $msg = $model->where('template_id',$template_id['value'])->first();
        $page = $msg['page'].'?'.$prama;

//        Logger::getInstance()->log('$user:\n'.json_encode($user),'user-test');
        //判断是否有可以formId
        $cache =  new Cache();
        //根据openid取找到相应的openid的formid的集合，先删除该集合已过期的所有的formid,
        $cache->zRemRangeByScore($adminOpenid,0,time()+10);
        //然后取一个formid的值
        $formid_array = $cache->zRange($adminOpenid,0,0);
//        Logger::getInstance()->log('formid_array:'.PHP_EOL.json_encode($formid_array),'user-test');
        if(count($formid_array) == 0){
            return $this->writeJson(1,null,'没有可用的FORMID了！');
        }
        $formid = $formid_array[0];
        $appletModel = $this->appletArticleModel($applet);
        $ArticlesMeiwenModel = new $appletModel;
        $articlesInfo = $ArticlesMeiwenModel->select('id,title')->find($id);
        $msg['keywords'][0]->keyword2 = $articlesInfo['title'];
        $wechat = new MiniProgram($applet);
        $sendData = [
            'touser'      => $adminOpenid,
            'template_id' => $msg['template_id'],
            'page'        => $page,
            'form_id'     => $formid,
            'data'        => $msg['keywords'][0],
            'emphasis_keyword' => '',
        ];
        $result = $wechat->sendTemplateMessage($sendData);
        if($result['errcode'] == 0){
            //从集合中移除该formid
            $cache->zrem($adminOpenid,$formid);
            //如果删除集合中过期的formid值后该集合为空，则删除对应的小程序的openid集合中的openid元素
            if($cache->zCard($adminOpenid) == 0) $cache->srem($applet,$applet.'*'.$adminOpenid);
            return $this->writeJson(0, null, '推送成功');
        }else{
            if(($result['errcode'] == 41028) || ($result['errcode'] == 41029)){
                //从集合中移除该formid
                $cache->zrem($adminOpenid,$formid);
                //如果删除集合中过期的formid值后该集合为空，则删除对应的小程序的openid集合中的openid元素
                if($cache->zCard($adminOpenid) == 0) $cache->srem($applet,$applet.'*'.$adminOpenid);
            }
            return $this->writeJson(1, $result, '推送失败，'.$result['chmsg']);
        }

    }

    /**
     * 更新状态
     * @return bool
     */
    public function updateStatus(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $applet = $request->getRequestParam('applet') ?? '';
        if(!$applet){
            return $this->writeJson(1, null, 'applet参数错误！');
        }
        if(!isset($data['id']) || !$data['id']){
            return $this->writeJson(1, null, 'id参数错误！');
        }
        $appletModel = $this->appletArticleModel($applet);
        $model = new $appletModel;
        //修改
        $isUpdate = $model->update($data);
        if($isUpdate){
            return $this->writeJson(0,null,'更新成功');
        }else{
            return $this->writeJson(1,null,'更新失败，稍后重试');
        }

    }
}
